//
//  HubuViewController.m
//  iHubu2
//
//  Created by hanshui on 12-10-31.
//  Copyright (c) 2012年 hanshui. All rights reserved.
//

#import "HubuViewController.h"
#import "AdViewController.h"
#import "HubuFirstViewController.h"
#import "HubuSecondViewController.h"
#import "HubuThirdViewController.h"
#import "HubuFourthViewController.h"
#import "HubuFifthViewController.h"
#import "CommonUtil.h"
#import "TableCell3.h"
#import "HubuShelfViewController.h"

static NSUInteger kNumberOfPages = 5;

@interface HubuViewController ()

@end

@implementation HubuViewController
@synthesize columnScrollView, columnPageControl, columnViewControllers;
@synthesize column0Button, column1Button, column2Button, column3Button, column4Button;
@synthesize columnButtonUnderLineLabel;

@synthesize downloadButtonTag, downloadKB, downloadView;
@synthesize downloadTitle, downloadProgressView;
@synthesize isDownloading, downloadingButtonTitle;

@synthesize waitingView,waitingStateView, waitingViewContainer, waitingLabel;

- (void)dealloc
{

    [columnScrollView release];
    [columnPageControl release];
    [columnViewControllers release];
    
    [column0Button release];
    [column1Button release];
    [column2Button release];
    [column3Button release];
    [column4Button release];
    
    [downloadingButtonTitle release];
    [downloadKB release];
    [downloadView release];
    [downloadTitle release];
    [downloadProgressView release];
    
    [waitingView release];
    [waitingLabel release];
    [waitingViewContainer release];
    [waitingStateView release];
    
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
	NSMutableArray *controllers = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < kNumberOfPages; i++) {
        [controllers addObject:[NSNull null]];
    }
    self.columnViewControllers = controllers;
    [controllers release];
	
    columnScrollView.pagingEnabled = YES;
    columnScrollView.contentSize = CGSizeMake(columnScrollView.frame.size.width * kNumberOfPages, columnScrollView.frame.size.height);
    columnScrollView.showsHorizontalScrollIndicator = NO;
    columnScrollView.showsVerticalScrollIndicator = NO;
    columnScrollView.scrollsToTop = NO;
    columnScrollView.delegate = self;
	
    columnPageControl.numberOfPages = kNumberOfPages;
    columnPageControl.currentPage = 0;
	
    [self columnLoadScrollViewWithPage:0];
    [self columnLoadScrollViewWithPage:1];
}


#pragma mark -
#pragma mark scroll ad for finger spinning

- (void)columnLoadScrollViewWithPage:(int)page {
    if (page < 0) return;
    if (page >= kNumberOfPages) return;
	
    /*
    AdViewController *controller = [adViewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null]) {
        controller = [[AdViewController alloc] initWithPageNumber:page];
        [adViewControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
    }*/
    UIViewController *controller = [columnViewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null]) {
        if(page == 0) {
            controller = [[HubuFirstViewController alloc]  initWithNibName:@"HubuFirstViewController" bundle:nil];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        } else if(page == 1) {
            controller = [[HubuSecondViewController alloc] initWithNibName:@"HubuSecondViewController" bundle:nil];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        } else if(page == 2) {
            controller = [[HubuThirdViewController alloc] initWithNibName:@"HubuThirdViewController" bundle:nil];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        } else if(page == 3) {
            controller = [[HubuFourthViewController alloc] initWithNibName:@"HubuFourthViewController" bundle:nil];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        } else if(page == 4) {
            controller = [[HubuFifthViewController alloc] initWithNibName:@"HubuFifthViewController" bundle:nil];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        } else {
            controller = [[AdViewController alloc] initWithPageNumber:page];
            [columnViewControllers replaceObjectAtIndex:page withObject:controller];
            [controller release];
        }
    }
	
    if (nil == controller.view.superview) {
        CGRect frame = columnScrollView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
        controller.view.frame = frame;
        [columnScrollView addSubview:controller.view];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    if (columnPageControlUsed) {
        return;
    }
	
    CGFloat pageWidth = columnScrollView.frame.size.width;
    int page = floor((columnScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    columnPageControl.currentPage = page;
	
    [self columnLoadScrollViewWithPage:page - 1];
    [self columnLoadScrollViewWithPage:page];
    [self columnLoadScrollViewWithPage:page + 1];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    columnPageControlUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	columnPageControlUsed = NO;
    
    CGFloat pageWidth = columnScrollView.frame.size.width;
    int page = floor((columnScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    //columnPageControl.currentPage = page;
    [self setColumnButtonStyle:page];
}

- (IBAction)columnPageControlValueChanged:(id)sender {
    int page = columnPageControl.currentPage;
	
    [self columnLoadScrollViewWithPage:page - 1];
    [self columnLoadScrollViewWithPage:page];
    [self columnLoadScrollViewWithPage:page + 1];
    
    CGRect frame = columnScrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [columnScrollView scrollRectToVisible:frame animated:YES];
    
    columnPageControlUsed = YES;
}


- (IBAction)columnButtonClick:(id)sender {
    int tag = ((UIButton *)sender).tag;/*0,1,2,3,4*/
    int page = tag;
	
    [self columnLoadScrollViewWithPage:page - 1];
    [self columnLoadScrollViewWithPage:page];
    [self columnLoadScrollViewWithPage:page + 1];
    
    CGRect frame = columnScrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [columnScrollView scrollRectToVisible:frame animated:YES];
    
    columnPageControlUsed = YES;
    [self setColumnButtonStyle:page];
}


- (void)setColumnButtonStyle:(NSUInteger) columnIndex {
    [column0Button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [column1Button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [column2Button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [column3Button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    [column4Button setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    
    CGPoint underlineCenter = columnButtonUnderLineLabel.center;
    
    switch (columnIndex) {
        case 0: {
            [column0Button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            underlineCenter.x = column0Button.center.x;
            break;
        }
        case 1: {
            [column1Button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            underlineCenter.x = column1Button.center.x;
            break;
        }
        case 2: {
            [column2Button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            underlineCenter.x = column2Button.center.x;
            break;
        }
        case 3: {
            [column3Button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            underlineCenter.x = column3Button.center.x;
            break;
        }
        case 4: {
            [column4Button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            underlineCenter.x = column4Button.center.x;
            break;
        }
        default:
            break;
    }
    
    [UIView beginAnimations:@"movement" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.2];
    columnButtonUnderLineLabel.center = underlineCenter;
    
    [UIView commitAnimations];
}



-(void)checkBookList {
    //当有网络连接时，检查新书
    if([CommonUtil isConnected]) {
        [self showStatePad:@"" msg:@"正在更新图书信息..." interval:0];
        //获取本地最后的审批时间，以此为临界点检查服务端是否有新书发布
        if(lastApproval == nil){
            lastApproval = [[NSString alloc] init];
        }
        DBUtil *db = [[DBUtil alloc] init];
        [db openDB];
        lastApproval = [db getLastApprovalTime];
        [db closeDB];
        [db release];
        if(lastApproval == nil || [lastApproval isEqualToString:@""]) {
            lastApproval = @"0";
        }
        //NSLog(@"lastApproval:%@", lastApproval);
        //lastApproval = @"0";
        //去服务端检查新书，如果有则返回最新的50本图书
        if(ws == nil){
            ws = [[CommonWebServices alloc] init];
            [ws setDelegate:self];
        }
        [ws getWebServicesData:lastApproval page:@"1"];
        remotePageIndex = 1;
    }else{
        [self showStatePad:@"icon_disconnect_24.png" msg:@"无法连接到服务器，请检查网络连接..." interval:5];
    }
}

//从第二页开始是循环检查图书
-(void)checkBookListFromPage2 {
    //当有网络连接时，检查新书
    if([CommonUtil isConnected]) {
        if(ws == nil){
            ws = [[CommonWebServices alloc] init];
            [ws setDelegate:self];
        }
        [ws getWebServicesData:lastApproval page: [NSString stringWithFormat:@"%d", remotePageIndex]];
    }
}

//-(void)stopAllWaitAnimating {
//    [allWaitingView stopAnimating];
//}


//将返回的数据写入本地数据表
- (void)onCommonWebServicesOver:(NSDictionary *) dic {
    //NSLog(@"onCommonWebServicesOver");
    NSMutableArray *tmpData = [[NSMutableArray alloc] initWithCapacity:20];
    
    if([dic objectForKey:@"dataTable"] != nil) {
        tmpData = [dic objectForKey:@"dataTable"];
        //NSLog(@"tmpData:%d", [tmpData count]);
        if([tmpData count] > 0){
            //插入到本地数据库
            DBUtil *db = [[DBUtil alloc] init];
            [db openDB];
            [db insertData:tmpData];
            [db closeDB];
            [db release];
            
            //如果获取的数量小于50，则是最后一页，此时更新本地图书试图
            if([tmpData count] < 50) {
                
                [self showStatePad:@"icon_finished_24.png" msg:@"更新图书信息，完成！" interval:3];
            }else{//继续下一页的数据抽取
                remotePageIndex++;
                //[self checkBookListFromPage2];
                [self performSelector:@selector(checkBookListFromPage2) withObject:nil afterDelay:2.0];
            }
        }else{
            [self showStatePad:@"icon_finished_24.png" msg:@"更新图书信息，完成！" interval:3];
        }
    }else{
        [self showStatePad:@"icon_finished_24.png" msg:@"更新图书信息，完成！" interval:3];
    }
    [tmpData release];
}

- (void)onCommonWebServicesFaild {
    //NSLog(@"onCommonWebServicesFaild");
}


- (void)downloadStart:(CGPoint)targetPoint bookItem:(BookItem *)downloadItem {
    downloadPadFromPoint = targetPoint;
    downloadBookItem = [downloadItem mutableCopy];
    
}

- (void)downloadStartNow {
    downloadView.frame = CGRectMake(downloadPadFromPoint.x - 420, downloadPadFromPoint.y - 20, 200, 36);
    [downloadView setHidden:NO];
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [downloadView setFrame:CGRectMake(60, 2, 200, 36)];
    [UIView commitAnimations];
    
    downloadManager=[[DownloadManager alloc] init];
    downloadManager.title = [downloadBookItem bookName];
    NSString *fileName = @"";
    
    if([downloadBookItem book4PhoneResourceType] != nil && ![[downloadBookItem book4PhoneResourceType] isEqualToString:@""]) {
        downloadManager.fileURL=[NSURL URLWithString:[NSString stringWithFormat: @"%@files/this_is_source_folder/phone/%@_3.%@", kServerURL, [downloadBookItem bookId], [downloadBookItem book4PhoneResourceType]]];
        //downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:[localBookItem book4PadResource]];
        fileName = [[downloadBookItem book4PhoneResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [downloadBookItem book4PhoneResourceType]];
    }else{
        downloadManager.fileURL=[NSURL URLWithString:[NSString stringWithFormat: @"%@files/this_is_source_folder/pad/%@_4.%@", kServerURL, [downloadBookItem bookId], [downloadBookItem book4PadResourceType]]];
        //downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:[localBookItem book4PadResource]];
        fileName = [[downloadBookItem book4PadResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [downloadBookItem book4PadResourceType]];
    }
    
    downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:fileName];
    downloadManager.delegate = self;
    [downloadManager start];
}

-(IBAction) cancleDownload:(id)sender{
    [downloadManager cancelLoadAction:nil];
    [downloadView setHidden:YES];
    UIButton *currentDownloadButton = (UIButton *)[self.view viewWithTag:downloadButtonTag];
    if(currentDownloadButton != nil && [currentDownloadButton isKindOfClass:NSClassFromString(@"UIButton")]) {
        currentDownloadButton.enabled = YES;
        [currentDownloadButton setTitle:downloadingButtonTitle forState:UIControlStateNormal];
    }
    isDownloading = FALSE;
}


- (void) downloadManagerDataDownloadFinished: (NSString *) fileName {
    
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db updateBook:@"down" key:[downloadBookItem bookId] value:@"1"];
    [db closeDB];
    [db release];
    
    UIButton *currentDownloadButton = (UIButton *)[self.view viewWithTag:downloadButtonTag];
    if(currentDownloadButton != nil && [currentDownloadButton isKindOfClass:NSClassFromString(@"UIButton")]){
        //currentDownloadButton.enabled = NO;
        //[currentDownloadButton setTitle:@"已下载" forState:UIControlStateNormal];
        currentDownloadButton.enabled = YES;
        [currentDownloadButton setTitle:@"阅读" forState:UIControlStateNormal];
        TableCell3 *tableCell3 = (TableCell3 *)[self.view viewWithTag:downloadButtonTag + 400000];
        if(tableCell3 != nil) {
            [currentDownloadButton removeTarget:tableCell3 action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [currentDownloadButton addTarget:tableCell3 action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    /*
     if(currentDownloadButton != nil && [currentDownloadButton isKindOfClass:NSClassFromString(@"UIButton")]){
     currentDownloadButton.enabled = NO;
     [currentDownloadButton setTitle:@"已下载" forState:UIControlStateNormal];
     }*/
    //    [currentDownloadButton removeTarget:[currentColumnButton superview] action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [currentDownloadButton addTarget:[currentColumnButton superview] action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    /*
     [buyButton setTitle:@"阅读" forState:UIControlStateNormal];
     [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
     [buyButton addTarget:self action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
     [buyButton setEnabled:YES];
     */
    isDownloading = FALSE;
}
- (void) downloadManagerDataDownloadFailed: (NSString *) reason {
	NSLog(@"download failed:%@", reason);
    isDownloading = FALSE;
}


-(void)showStatePad:(NSString *)imageName msg:(NSString *)msg interval:(int)seconds {
    if([imageName isEqualToString:@""]) {
        [waitingStateView setHidden:YES];
        [waitingView startAnimating];
    }else{
        [waitingView stopAnimating];
        waitingStateView.image = [UIImage imageNamed:imageName];
        [waitingStateView setHidden:NO];
    }
    waitingLabel.text = msg;
    [waitingViewContainer setHidden:NO];
    
    if(seconds > 0){
        [self performSelector:@selector(hiddenStatePad) withObject:nil afterDelay:(NSTimeInterval)seconds];
    }
}

-(void)hiddenStatePad {
    [waitingViewContainer setHidden:YES];
}

-(IBAction)shelfClick:(id)sender {
    HubuShelfViewController *controller = [[HubuShelfViewController alloc]
                                            initWithNibName:@"HubuShelfViewController" bundle:nil];
    [controller showBookStoreView];
	//controller.modalPresentationStyle = UIModalPresentationFormSheet;
	//controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	//[self presentModalViewController: controller animated: YES];
    [self.navigationController pushViewController:controller animated:YES];
    
	//controller.view.superview.frame = CGRectMake(0, 0, 320, 460);
}
@end
